<?php

namespace App\Http\Resources\posts;

use App\Models\posts\Posts;
use Illuminate\Http\Resources\Json\ResourceCollection;

class PostsPageCollection extends ResourceCollection
{

    protected $add = [];
    public function __construct($resource,$add = [])
    {
        parent::__construct($resource);

        $this->resource = $this->collectResource($resource);
        $this->add = $add;
    }
    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        $collection = $this->collection;
        if (!empty($this->add)){
            $collection = $collection->filter(function ($item){
                return $item->id != $this->add->id;
            });
            $collection->prepend($this->add);
        }
        return [
            'total' => $this->resource->total(),
            'perPage' => $this->resource->perPage(),
            'current_page' => $this->resource->currentPage(),
            'items' => $collection->map(function ($item) {
                return new PostsResource($item);
            })
        ];

    }
}
